// pages/add/add.js
const db = wx.cloud.database(
  {env: 'yun1-7glegjwn33768ff6'}
)
const memo = db.collection('memocyou')
Page({
  data:{
    show: false,
    title:'',
    value:'',
    radio:'1',
    status:0,
    fileList:[],
    fileID:[],
    cloudPath:[],
    newFileList:[],
  },
  delimg(event){
    let fileList= this.data.fileList;
    this.data.fileList.splice(event.detail.index,1)
    this.setData({fileList})
  },
  
  afterRead(event) {
    const { file } = event.detail;
    const fileList=this.data.fileList
    const newFileList=event.detail.file.map((item,index)=>{return {'url':item.url}});
    fileList.push(...newFileList);
    console.log(fileList);
    this.setData({
      file,fileList
    })
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  },
  
  // 上传图片
  async uploadToCloud() {
    wx.cloud.init();
    const { fileList } = this.data;
    if (!fileList.length) {
      wx.showToast({ title: '未选择图片', icon: 'none' });
    } else {
      console.log('1')
      const uploadTasks = fileList.map((file, index) => this.uploadFilePromise(new Date().getTime()+'.png', file));
      console.log('2') ;
      //此处若不使用await则会进入microtask队列影响其他函数执行顺序
      await Promise.all(uploadTasks).then(data => {
          wx.showToast({ title: '上传成功', icon: 'none' });
          const newFileList = data.map((item) => {return {url: item.fileID}});
          this.setData({ 
            cloudPath: data, 
            fileList: newFileList,
          });
          console.log('3') 
        })
        .catch(e => {
          wx.showToast({ title: '上传失败', icon: 'none' });
          console.log(e);
        });
        console.log('4');
       
    }
  },
  uploadFilePromise(fileName, chooseResult) {
    return wx.cloud.uploadFile({
      cloudPath: fileName,
      filePath: chooseResult.url
    });
  },
  showPopup() {
    this.setData({ show: true });
  },
  onClose() {
    this.setData({ show: false });
  },
  radioChange(event) {
    if(event.detail==2){
      this.data.status=1
    }else{
      this.data.status=0
    }
    this.setData({
      radio: event.detail,

    });
    console.log(event)
  },
  onChange(event) {
    // event.detail 为当前输入的值
    console.log(event.detail);
  },
  async add(event){
    await this.uploadToCloud();
    wx.cloud.callFunction({
        name:'add',
        data:{
            title:this.data.title,
            value:this.data.value,
            border:this.data.radio,
            status:this.data.status,
            imgfileID:this.data.cloudPath.map((item,index)=>{return {'fileID':item.fileID}}),
            
        }
    }).then(res=>{
      console.log(res);
      wx.navigateBack({
        delta: 0,
      })
    }).catch(console.error)
  
  }
})